package cn.kgc.watch.service.impl;

import cn.kgc.watch.entity.Cart;
import cn.kgc.watch.entity.CartShopping;
import cn.kgc.watch.mapper.CartMapper;
import cn.kgc.watch.mapper.CartShoppingMapper;
import cn.kgc.watch.service.CartShoppingService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class CartShoppingServiceImpl implements CartShoppingService {
    @Resource
    private CartShoppingMapper cartShoppingMapper;
    @Resource
    private CartMapper cartMapper;

    /**
     *刷新总价
     * @param cartShoppingid
     */
    public void refresh(Integer cartShoppingid){
        Integer cartId = this.cartShoppingMapper.selectCartId(cartShoppingid);
        Cart cart = this.cartMapper.selectCartById(cartId);
        Double price = 0.0;
        if(cart!=null) {
            for (CartShopping cartShoppings : cart.getCartShoppingList()) {
                price = price + cartShoppings.getTotalPrice();
            }
        }
        this.cartMapper.updateCart(cart.getId(),price);
    }
    /**
     * 刷新总计
     * **/
    public void refreshModify(Integer cartId){
        Cart cart = this.cartMapper.selectCartById(cartId);
        Double price = 0.0;
        if(cart!=null) {
            for (CartShopping cartShoppings : cart.getCartShoppingList()) {
                price = price + cartShoppings.getTotalPrice();
            }
        }
        this.cartMapper.updateCart(cart.getId(),price);
    }
    @Override
    public void dec(CartShopping cartShopping) {
        this.cartShoppingMapper.decInc(cartShopping);
        this.refresh(cartShopping.getId());
    }

    @Override
    public void inc(CartShopping cartShopping) {
        this.cartShoppingMapper.decInc(cartShopping);
        this.refresh(cartShopping.getId());
    }

    @Override
    public void removeCartShopping(Integer cartShoppingId) {
        Integer id = this.cartShoppingMapper.selectCartId(cartShoppingId);
        this.cartShoppingMapper.deleteCartShopping(cartShoppingId);
        this.refresh(cartShoppingId);
    }

    @Override
    public void addCartShopping(CartShopping cartShopping) {
        cartShopping.setCreateTime(new Date());
        this.cartShoppingMapper.insertCartShopping(cartShopping);
        this.refresh(cartShopping.getId());
    }

    @Override
    public Integer findCartShoppingById(Integer id) {
        return this.cartShoppingMapper.selectCartShoppingById(id);
    }

    @Override
    public void modifyCartShopping(CartShopping cartShopping) {
        this.cartShoppingMapper.updateCartShopping(cartShopping);
        this.refreshModify(cartShopping.getCart().getId());
    }
}
